package com.tungse.juc.volatile_test;

import java.util.concurrent.atomic.AtomicInteger;

public class Volatile_Demo2 {

    //volatile不保证原子性
    private static volatile int num = 0;
    private static AtomicInteger num2 = new AtomicInteger(0);
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                for (int j = 0; j < 1000; j++) {
                    addOne();
                }
            }).start();
        }
        while(Thread.activeCount() > 2){
            Thread.yield(); //礼让线程
        }
        System.out.println(num);
        System.out.println(num2.get());
    }


    public static void addOne(){
        num++;//不是一个原子性操作
        num2.incrementAndGet();
    }
}
